﻿/*
SharpContent
Copyright (c) 2002-2009, State of Montana

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the State of Montana nor the names of contributors may be used to endorse
or promote products derived from this software without specific prior
written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.
*/

(function() {
	ValidationException = new Class({
		initialize: function(spec, prop) {
			this.spec = spec;
			this.invalidProp = spec[prop];
			this.message = spec.errorMessage;
		}
	});
	
	// TODO: SharpHelpers might be a better name for this module
	var window = this, sharplib = window.sharplib = {
		genericField: function(tag, id, name) {
			return new Element(tag, {
				name: name,
				id: id
			});
		},
		inputField: function(type, id, name) {
			var field = new sharplib.genericField('input', id, name);
			if (type)
				field.type = type;
			return field;
		},
		// TODO: Handle more options here for size, readonly, disabled, maxlength, alt, et cetera
		fieldMakers: {
			'text': {
				'makeLabel': function(labelFor, labelText, options) {
					return new Element('label', { 'for': labelFor }).appendText(labelText);
				},
				'makeField': function(fieldId, value, options) {
					var field = new sharplib.inputField('text', fieldId, fieldId);
					if (options) {
						field.size = options.has('size') ? size : 30;
						if (options.has('disabled') && options['disabled']) {
							field.setProperty('disabled', true);
						}
					}
					if (value)
						field.value = value;
					return field;
				}
			},
			'textarea': {
				'makeLabel': function(labelFor, labelText, options) {
					return new Element('label', { 'for': labelFor }).appendText(labelText);
				},
				'makeField': function(fieldId, value, options) {
					var field = new sharplib.genericField('textarea', fieldId, fieldId);
					if (value)
						field.value = value;
					if (options) {
						if (options.has('rows'))
							field.rows = options.rows;
						if (options.has('cols'))
							field.cols = options.cols;
					}
					return field;
				}
			},
			'radio': {
				'makeLabel': false,
				'makeField': function(fieldId, value, options) {
					var container = new Element('span');
					if (options && options.has('values')) {
						options.values.each(function(val) {
							var field = new sharplib.inputField('radio', fieldId + ' ' + val, fieldId);
							field.value = val;
							if (value == val)
								field.checked = true;

							container.grab(new Element('div').grab(field).grab(new Element('span', { 'text': field.value })));
						});
					}
					return container;
				}
			},
			'checkbox': {
				'makeLabel': function(labelFor, labelText, options) {
					return new Element('label', { 'for': labelFor }).appendText(labelText);
				},
				'makeField': function(fieldId, value, options) {
					var field = new sharplib.inputField('checkbox', fieldId, fieldId);
					field.setStyle('width', '20px');
					field.setStyle('margin', '5px 60% 10px 10px');
					if (value == "true" || value == true || value == "on") {
						field.setProperty('checked', 'true');
					}
					return field;
				}
			},
			'select': {
				'makeLabel': function(labelFor, labelText, options) {
					return new Element('label', { 'for': labelFor }).appendText(labelText);
				},
				'makeField': function(fieldId, value, options) {
					var field = new sharplib.genericField('select', fieldId, fieldId);
					field.setStyle('width', '75%');
					field.setStyle('float', 'left');
					field.setStyle('margin', '5px 0 0 10px');
					
					if (options && options.has('values')) {
						options.values.each(function(val, index) {
							var selOpt = new Element('option');
							if (val == value)
								selOpt.setProperty('selected', 'selected');
							selOpt.setProperty('value', val);
							selOpt.appendText(val);
							selOpt.inject(field);
						});
						return field;
					}
					return false;
				}
			},
			'multiselect': {
				'makeLabel': function(labelFor, labelText, options) {
					return new Element('label', { 'for': labelFor }).appendText(labelText);
				},
				'makeField': function(fieldId, value, options) {
					var field = new sharplib.genericField('select', fieldId, fieldId);
					field.setStyle('width', '75%');
					field.setStyle('float', 'left');
					field.setStyle('margin', '5px 0 0 10px');
					field.setProperty('multiple', 'multiple');
					if (options && options.has('values')) {
						options.values.each(function(val, index) {
							var selOpt = new Element('option');
							if (val == value)
								selOpt.setProperty('selected'); // todo : this needs to split a multiple value and select each node.
							selOpt.setProperty('value', val);
							selOpt.appendText(val);
							selOpt.inject(field);
						});
						return field;
					}
					return false;
				}
			}
		},
		fieldFromSpec: function(spec, item, options, idPrefix) {
			if (!spec.label)
				return null;
			var fieldType = spec.displayHint ? spec.displayHint : 'text',
				fieldMaker = sharplib.fieldMakers[fieldType],
				options = options ? options : new Hash();
			if (!fieldMaker)
				return undefined;

			var properties = item.getElementsByTagName(spec.propertyKey);

			// properties.length should be 1. if it's not, take the first one out of respect for the fallen
			if (item && properties && properties.length >= 1)
				var value = properties[0].textContent ? properties[0].textContent : properties[0].text;

				
			var isRequired = spec.required ? spec.required : false;
			var values = spec.values && spec.values.length > 0 ? spec.values : [];
			options.values = values;
			
			var label = spec.label;
			var fieldName = spec.fieldName;
			var errorMessage = spec.errorMessage ? spec.errorMessage : "Invalid value for " + label;
			fieldLabelPair = new Element('div', { 'id': spec.fieldId });
			if (fieldMaker.makeLabel)
				fieldLabelPair.grab(fieldMaker.makeLabel(fieldName, label, options));
			fieldLabelPair.grab(fieldMaker.makeField(idPrefix ? idPrefix + fieldName : fieldName, value ? value : null, options));
			fieldLabelPair.grab(new Element('span', { 'class': 'error', 'text': '*'}));
			return fieldLabelPair;
		},
		firstPropertyByKey: function(item, key) {
			props = item.ItemInstance.Properties.select(function(val) {
				if (val.Property) {
					return val.Property.KeyName.toLowerCase() == key.toLowerCase();
				} else {
					return false;
				}
			});

			rtn = props && props.length && props.length > 0 ? props[0] : props;
			if (rtn.Property && rtn.Property.KeyValue) {
				return rtn.Property;
			} else {
				return { KeyValue: "", KeyName: "" };
			}
		},
		saveItem: function(item, callback) {
			if (item) {
				mc.postItem(url, item, callback);
			}
		},
		makeItemSpecification: function(specs) {
			if (!specs || specs.length == 0)
				return null;

			// TODO: How do we enforce spec.allowUnknown? What does it mean?
			var propSpecs = specs.map(function(spec) {
				var newPropSpec = new Hash();

				isRequired = spec.getAttribute('required')
				newPropSpec.required = isRequired == "true" ? true : false;

				errorMessage = spec.getAttribute('errorMessage')
				if (errorMessage)
					newPropSpec.errorMessage = errorMessage;

				label = spec.getAttribute('label');
				if (label) {
					newPropSpec.label = label;
					var programmaticLabel = label.split(' ').reduce(function(prev, cur) {
						return prev + cur;
					}, '');
					newPropSpec.fieldName = programmaticLabel + 'Field';
					newPropSpec.fieldId = programmaticLabel + 'Id';
				}

				hint = spec.getAttribute('displayType');
				if (hint)
					newPropSpec.displayHint = hint.toLowerCase();

				values = spec.getAttribute('validValues')
				if (values)
					newPropSpec.values = values.split(',');

				editable = spec.getAttribute('userEditable');
				if (editable)
					newPropSpec.userEditable = editable == "true" ? true : false;

				// Pray that the validation expression is a valid JS regex...
				valRegExp = spec.getAttribute('validationExpression');
				if (valRegExp)
					newPropSpec.validationExpression = new RegExp(valRegExp);

				newPropSpec.propertyKey = spec.tagName;
				
				return newPropSpec;
			});
			
			return propSpecs;
		},
		getItemSpecification: function(item) {
			/*
			Called by panes when they want to create output conforming to an item specification.
			Panes are not required to do this.
			Panes are allowed to pick and choose which fields to display.
			*/
			var rp = item.getElementsByTagName('mc:resourceprovider')[0],
				pid = rp.textContent ? rp.textContent : rp.text,
				specXml = new Array(), 
				mcsSpec, 
				mcSpec;

			if (sharpRegistry.itemSpecifications.has(pid))
				return sharpRegistry.itemSpecifications[pid];
				
			if (item.getElementsByTagNameNS) {
				var mcsUri = item.lookupNamespaceURI('mcs'),
					mcUri = item.lookupNamespaceURI('mc');
					
				mcsSpec = item.getElementsByTagNameNS(mcsUri, '*');
				mcSpec = item.getElementsByTagNameNS(mcUri, '*');
			} else {
				mcsSpec = item.getElementsByTagName('mcs:*');
				mcSpec = item.getElementsByTagName('mc:*');
			}
			
			if (!mcsSpec || mcsSpec.length == 0)
				return null;
				
			specXml.append = this.appendHtmlCollectionToArray;
			specXml.append(mcsSpec);
			specXml.append(mcSpec);
			
			if (specXml && specXml.length > 0) {
				sharpRegistry.itemSpecifications[pid] = sharplib.makeItemSpecification(specXml);
				return sharpRegistry.itemSpecifications[pid];
			} else {
				return null;
			}
		},
		appendHtmlCollectionToArray: function(collection) {
			var collectionLength = collection.length;
			for (i = 0; i < collectionLength; i++)
			{
				if(!collection[i])
					continue;
				this.push(collection[i]);
			}
		},
		getBaseItemDav: function(item) {
			var responses = item.getElementsByTagName('D:response');
			if (!responses || responses.length == 0)
				return null;

			if (responses.length == 1) {
				return responses[0];
			} else {
				// TODO: Can the "root" item of a multi-response propfind ever not be the 0th item?
				return responses[0];
			}
		},
		getItemMimeType: function(item) {
			var mimeType = item.getElementsByTagName('mc:mimetype')[0];
			if (!mimeType)
				return null;
				
			return mimeType.textContent ? mimeType.textContent : mimeType.text;
		}
	};
})();
